/**
 * HomeController
 *
 * @description :: Server-side logic for managing homes
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var moment = require('moment');
var request = require('request');

module.exports = {
  index: function (req, res) {
    var Promise = require('promise');
    Token.find({type: 'access_token'}).then(function (result) {
      var now = moment().valueOf();
      if (now - result[0].createTime < result[0].expire) {
        //console.log(now - result.createTime);
        return result[0].value;
      } else {
        return result[0].type;
      }
    }).then(function (token) {
      console.log(token);
      req.session.accessToken = token;
      res.view('index');
    }).catch(function (err) {
      res.serverError(err);
    });

  },

  login: function (req, res) {
    if (req.params.name == 'admin') {
      req.session.openId = 'admin123456';
      res.redirect('home');
    }
  },

  detail: function (req, res) {
    res.view('detail');
  },

  access: function (req, res) {
    request('http://www.baidu.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
      res.send(response);
    });
  },

  msg: function (req, res) {
    request.post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=mP06jN6kJERWFnHonPUbbV6wAbRBsrFf1ekROTT7Y7BEIITTaR1B24xINciIn3N6', {form: {
      "touser": "steph",
      "msgtype": "text",
      "agentid": 11,
      "text": {
        "content": "Holiday Request For Pony(http://xxxxx)"
      },
      "safe":0
    }}, function (err, response, body) {
      console.log(body);
      res.send(response);
    })
  }
}


